package com.shanzmoo.job.task;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanzmoo.base.constant.MallOrderStatus;
import com.shanzmoo.db.mall.entity.MallOrderEntity;
import com.shanzmoo.db.mall.service.IMallOrderService;
import com.shanzmoo.job.base.BaseTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 商城订单取消任务
 *
 * @author： Gzhao 2021/2/9
 */
@Slf4j
@Component(value = "mallOrderCancelTask")
public class MallOrderCancelTask implements BaseTask {

    private static final String ORDER_CANCEL_DESCRIPTION = "超过2小时未支付，系统自动取消订单";

    private static final Integer CURRENT_USER = 1;

    @Autowired
    private IMallOrderService mallOrderService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String doJob(){

        String deadline = LocalDateTimeUtil.formatNormal(LocalDateTimeUtil.offset(LocalDateTime.now(), -2, ChronoUnit.HOURS));
        List<MallOrderEntity> list = mallOrderService.list(
                new QueryWrapper<MallOrderEntity>()
                        .eq("deleted", false)
                        .eq("pay_status", MallOrderStatus.WAIT_PAY)
                        .lt("create_time", deadline)

        );

        for (MallOrderEntity mallOrderEntity : list) {
            mallOrderEntity.setStatus(MallOrderStatus.CLOSED);

            mallOrderService.updateById(mallOrderEntity);
            mallOrderService.saveOperateLog(mallOrderEntity.getId(), ORDER_CANCEL_DESCRIPTION, CURRENT_USER);
        }

        return "success";
    }
}
